local args = ngx.req.get_uri_args()

local act_id = args.act_id

if nil == act_id then
    ngx.say('{"code":10000, "message":"act_id不能为空", "data":{"allowed": false, "type":"can-not-found"}}')
    return
end

local redis_client = require "lib.redis"
local redis = redis_client:new()

--开始投票
local vote = redis:hmget('rules:'..act_id, 'limit', 'type', 'start_at', 'end_at', 'pause')

if nil == vote then
    ngx.say('{"code":10000, "message":"活动不存在", "data":{"allowed": false, "type":"not-found"}}')
    return
end

local is_paused = tonumber(vote[5])

--验证活动是否暂停
if is_paused == 1 then
    ngx.say('{"code":10000, "message":"活动已暂停", "data":{"allowed": false, "type":"paused"}}')
    return
end

local time = ngx.time()
local start_at = vote[3] or 0
local end_at = vote[4] or (time + 1)

--验证投票时间
if time > tonumber(end_at) then
    ngx.say('{"code":10000, "message":"活动已经结束", "data":{"allowed": false, "type":"act-end"}}')
    return
end

if time < tonumber(start_at) then
    ngx.say('{"code":10000, "message":"活动还未开始", "data":{"allowed": false, "type":"act-not-start"}}')
    return
end

-- 验证参数
local user_id = args.uid

if nil == user_id then
    ngx.say('{"code":10000,"message":"您没有登录", "data":{"allowed": false, "type":"no-login"}}')
    return
end

--local vote_token = args.vote_token
--if nil == vote_token then
--    ngx.say('{"code":10000,"message":"vote_token不能为空", "data":{"allowed": false, "type":"can-not-found"}}')
--    return
--end

--local user, err = redis:hget('app:uid:'..act_id, user_id)

-- 验证是否登录
--if nil == user then
--    ngx.say('{"code":10000,"message":"您没有登录", "data":{"allowed": false, "type":"no-login"}}')
--    return
--end

-- 判断验签是否正确
--if vote_token ~= user then
--    ngx.say('{"code":10001,"message":"验签不正确", "data":{"allowed": false, "type":"no-login"}}')
--    return
--end

--local ways = args.ways
-- 删除验签
--if ways ~= "wechat" then
--    redis:hset('app:uid:'..act_id, user_id, '')
--end

-- 验证投票次数，防刷票
local times_key = table.concat({"times", act_id, user_id}, ":")
local limit = tonumber(vote[1])
local mode = vote[2]

if mode == 'day' then
    local times_of_everday = redis:hget(times_key, ngx.today())
    local t = tonumber(times_of_everday) or 0
    if t >= limit then
        ngx.say('{"code":10000, "message":"您今天的投票次数已用完", "data":{"allowed": false, "type":"no-times"}}')
        return
    end
else
    local times_of_life = redis:hget(times_key, 'total')
    local t = tonumber(times_of_life) or 0
    if t >= limit then
        ngx.say('{"code":10000, "message":"您的投票次数已用完", "data":{"allowed": false, "type":"no-times"}}')
        return
    end
end

ngx.say('{"code":200, "message":"success", "data":{"allowed": true,"type":null}}')
